package com.camera.common;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;

/**
 * @Classname HttpClient
 * @Description TODO
 * @Date 2025/3/10 14:12
 * @Created by xxx
 */
public class HttpClient {

    public static Path downloadWithProperExt(String imageID, String url, String saveDir) throws IOException {
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

        // 获取真实文件名
        String fileName = getFileName(conn);
        if (fileName.isEmpty()) {
            fileName = imageID + ".jpg";
        }

        // 生成安全文件名
        String safeFileName = fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
        Path savePath = Paths.get(saveDir, safeFileName);

        // 下载文件
        try (InputStream in = conn.getInputStream()) {
            Files.copy(in, savePath, StandardCopyOption.REPLACE_EXISTING);
            return savePath;
        } catch (IOException e) {
            return null;
        }
    }

    // 综合获取文件名
    private static String getFileName(HttpURLConnection conn) {
        // 1. 从Content-Disposition获取
        String disposition = conn.getHeaderField("Content-Disposition");
        if (disposition != null) {
            int filenameIndex = disposition.indexOf("filename=");
            if (filenameIndex != -1) {
                return disposition.substring(filenameIndex + 9)
                        .replaceAll("[\";]", "");
            }
        }

        // 2. 从URL路径获取
        String path = conn.getURL().getPath();
        String pathName = path.substring(path.lastIndexOf('/') + 1);
        if (!pathName.contains(".")) pathName = "";

        return !pathName.isEmpty() ? pathName : "";
    }

    /**
     * 发送POST请求并返回JSONObject
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return String 响应JSON字符串
     * @throws IOException 网络或I/O错误
     * @throws JSONObject  响应非JSON格式
     */
    public static String doPOST(String url, Map<String, String> params) throws IOException, JSONException {
        return doPOST(url, params, RequestType.JSON); // 默认使用JSON模式
    }

    /**
     * 发送POST请求（可指定请求类型）
     *
     * @param url    请求地址
     * @param params 请求参数
     * @param type   请求类型：JSON 或 FORM
     */
    public static String doPOST(String url, Map<String, String> params, RequestType type)
            throws IOException, JSONException {

        HttpURLConnection conn = null;
        try {
            // 1. 创建连接
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();

            // 2. 设置通用参数
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);    // 5秒连接超时
            conn.setReadTimeout(10000);      // 10秒读取超时
            conn.setDoOutput(true);

            // 3. 设置请求头
            if (type == RequestType.JSON) {
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
            } else {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }

            // 4. 构建请求体
            String requestBody;
            if (type == RequestType.JSON) {
                requestBody = new JSONObject(params).toString();
            } else {
                requestBody = buildFormData(params);
            }

            // 5. 发送请求数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 6. 处理响应
            int responseCode = conn.getResponseCode();
            if (responseCode < 200 || responseCode >= 300) {
                throw new IOException("HTTP Error Code: " + responseCode + " - " + conn.getResponseMessage());
            }

            return parseResponse(conn);

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    // 构建表单编码的请求体
    private static String buildFormData(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder formData = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (formData.length() > 0) {
                formData.append("&");
            }
            formData.append(URLEncoder.encode(entry.getKey(), String.valueOf(StandardCharsets.UTF_8)));
            formData.append("=");
            formData.append(URLEncoder.encode(entry.getValue(), String.valueOf(StandardCharsets.UTF_8)));
        }
        return formData.toString();
    }

    // 解析响应为JSON
    private static String parseResponse(HttpURLConnection conn) throws IOException, JSONException {
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }

    // 请求类型枚举
    public enum RequestType {
        JSON, FORM
    }

}

